package cn.teduymdj.jxc.service.impl;

import cn.teduymdj.jxc.ex.ServiceException;
import cn.teduymdj.jxc.mapper.GoodsMapper;
import cn.teduymdj.jxc.mapper.PurchaseListGoodsMapper;
import cn.teduymdj.jxc.mapper.PurchaseListMapper;
import cn.teduymdj.jxc.pojo.dto.*;
import cn.teduymdj.jxc.pojo.entity.PurchaseList;
import cn.teduymdj.jxc.pojo.entity.PurchaseListGoods;
import cn.teduymdj.jxc.pojo.vo.*;
import cn.teduymdj.jxc.service.PurchaseListGoodsService;
import cn.teduymdj.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 进货业务实现
 * 刘校权
 */
@Slf4j
@Service
@Transactional // 添加事务
public class PurchaseListGoodsServiceImpl implements PurchaseListGoodsService {

    @Autowired
    private PurchaseListMapper purchaseListMapper;
    @Autowired
    private PurchaseListGoodsMapper purchaseListGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;


    @Override
    public void save(PurchaseListAddNewDTO02 purchaseListAddNew) {
        log.debug("处理保存进货单信息的业务:{}", purchaseListAddNew);
        if (purchaseListAddNew.getPurchaseNumber()==null) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"保存失败,单号不能为空");
        }
        int purchaseNumber = purchaseListMapper.countByPurchaseNumber(purchaseListAddNew.getPurchaseNumber());
        // 查询单号是否存在
        if (purchaseNumber != 0) {
            // 是:添加失败，抛出异常，单号已存在
            String message = "保存进货单信息失败，单号已存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        PurchaseListAddNewDTO purchaseListAddNewDTO = new PurchaseListAddNewDTO();
        BeanUtils.copyProperties(purchaseListAddNew,purchaseListAddNewDTO);
        log.debug("即将插入进货单数据:{}",purchaseListAddNewDTO);
        int result = purchaseListMapper.insert(purchaseListAddNewDTO);
        // 判断是否添加成功
        if (result != 1) {
            // 否:添加失败，抛出异常，请稍后重试
            String message = "添加失败，服务器忙，请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        List<PurchaseListGoodsAddNewDTO> purchaseListGoodsAddNewDTOList = purchaseListAddNew.getTableData();
        if (purchaseListGoodsAddNewDTOList==null){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "保存进货单信息失败,进货单商品不存在!");
        }
        purchaseListGoodsAddNewDTOList.forEach(l->log.debug("即将插入进货单商品数据:{}",l));
        // 保存进货单商品信息
        for (PurchaseListGoodsAddNewDTO purchaseListGoodsAddNewDTO :purchaseListGoodsAddNewDTOList){
            //判断单价乘数量和总金额是否相等
            BigDecimal price = purchaseListGoodsAddNewDTO.getPrice();
            Integer num = purchaseListGoodsAddNewDTO.getNum();
            BigDecimal number = new BigDecimal(num);
            BigDecimal total = purchaseListGoodsAddNewDTO.getTotal();
            if (!price.multiply(number).equals(total)){
                throw new ServiceException(ServiceCode.ERR_INSERT,"保存进货单信息失败,插入金额有误!");
            }
            //通过id查询数据库信息是否存在
            Long goodsId = purchaseListGoodsAddNewDTO.getId();
            GoodsStandardVO goods = goodsMapper.getStandardById(goodsId);
            if (goods==null){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"保存进货单信息失败,商品不存在!");
            }
            //设置进货单id
            Long id = purchaseListAddNewDTO.getId();
            purchaseListGoodsAddNewDTO.setPurchaseListId(id);
            //
            // 修改商品上一次进货价，进货均价，库存，状态
            goods.setLastPurchasingPrice(purchaseListGoodsAddNewDTO.getPrice());
            goods.setInventoryQuantity(goods.getInventoryQuantity());
            int t = 2;
            BigDecimal two = new BigDecimal(t);
            goods.setPurchasingPrice(goods.getLastPurchasingPrice().multiply(purchaseListGoodsAddNewDTO.getPrice()).divide(two));
            goods.setState(2);
            GoodsAddNewDTO goodsAddNewDTO = new GoodsAddNewDTO();
            BeanUtils.copyProperties(goods,goodsAddNewDTO);
            goodsMapper.addNew(goodsAddNewDTO);
        }
        //插入进货商品实体表
        int rows = purchaseListGoodsMapper.insertBatch(purchaseListGoodsAddNewDTOList);
        if (rows!=1){
            throw new ServiceException(ServiceCode.ERR_INSERT,"保存进货单信息失败,服务器忙,请稍后再试!");
        }
    }

    @Override
    public List<PurchaseListListItemVO> getPurchaselist(SelectPurchaseListCondition selectPurchaseListCondition) {
        return purchaseListMapper.listByCondition(selectPurchaseListCondition);
    }

    @Override
    public List<PurchaseListGoodsListItemVO> getPurchaseListGoodsByPurchaseListId(Long purchaseListId) {
        return purchaseListGoodsMapper.listByListId(purchaseListId);
    }

    @Override
    public void delete(Long purchaseListId) {
        log.debug("开始处理删除进货单信息的业务:{}", purchaseListId);
        PurchaseListStandardVO queryResult = purchaseListMapper.getStandardById(purchaseListId);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "删除进货单失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = purchaseListMapper.deleteById(purchaseListId);
        if (rows < 1) {
            String message = "删除进货单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        //删除进货单商品表信息
       rows =  purchaseListGoodsMapper.deleteByPurchaseListId(purchaseListId);
        if (rows < 1) {
            String message = "删除进货单商品失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }


    }

    @Override
    public PurchaseList getPurchaseList(Long purchaseListId) {
        log.debug("开始处理获取进货单信息的业务:{}", purchaseListId);
        PurchaseListStandardVO standardById = purchaseListMapper.getStandardById(purchaseListId);
        if (standardById==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"获取的进货单不存在!");
        }
        PurchaseList purchaseList = new PurchaseList();
        BeanUtils.copyProperties(standardById,purchaseList);
        //t_user无对应的Mapper,purchaseList用户信息为null.
        return purchaseList;
    }

    @Override

    public void updateState(Integer state, Long id) {
        log.debug("开始处理获取进货单信息的业务:参数:state:{},id:{}", state,id);
        PurchaseListAddNewDTO purchaseListAddNewDTO = new PurchaseListAddNewDTO();
        purchaseListAddNewDTO.setEnable(state);
        purchaseListAddNewDTO.setId(id);
       int row = purchaseListMapper.update(purchaseListAddNewDTO);
       if (row!=1){
           throw new ServiceException(ServiceCode.ERR_UPDATE,"更新进货单状态失败,请稍后再试!");
       }
    }
    @Override
    public void setPaid(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setUnpaid(Long id) {
        updateEnableById(id, 2);
    }

    @Override
    public List<PurchaseListCountListItemVO> listByCondition(SelectReturnCondition selectReturnCondition) {

        return purchaseListGoodsMapper.listByCondition(selectReturnCondition);
    }

    private void updateEnableById(Long id, int isPaid) {
        PurchaseListStandardVO queryResult = purchaseListMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "修改支付状态失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断状态是否冲突（当前已经是目标状态）
        if (queryResult.getIsPaid().equals(isPaid)) {
            String message = "修改支付失败，进货单已经处于该状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        PurchaseListAddNewDTO purchaseList = new PurchaseListAddNewDTO();
        purchaseList.setId(id);
        purchaseList.setIsPaid(isPaid);
        int rows = purchaseListMapper.update(purchaseList);
        if (rows != 1) {
            String message = "修改支付失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public List<PurchaseListGoodsListItemVO> getPurchaseListGoodsByPurchaseListId(Long purchaseListId, Long goodsTypeId, String codeOrName) {
        return purchaseListGoodsMapper.list();
    }
}
